<template>
  <div class="forbidden-container">
    <div class="forbidden-content">
      <div class="error-icon">
        <el-icon size="120" color="#f56c6c">
          <Lock />
        </el-icon>
      </div>
      
      <h1 class="error-title">访问被拒绝</h1>
      <p class="error-description">
        {{ errorReasonText }}
      </p>
      
      <!-- 显示尝试访问的页面 -->
      <el-alert
        v-if="targetPageTitle"
        type="warning"
        :closable="false"
        show-icon
        style="margin: 20px 0;"
      >
        <template #title>
          尝试访问：{{ targetPageTitle }}
        </template>
      </el-alert>
      
      <div class="error-details">
        <el-card class="details-card">
          <template #header>
            <div class="card-header">
              <el-icon><InfoFilled /></el-icon>
              <span>权限信息</span>
            </div>
          </template>
          
          <div class="permission-info">
            <div class="info-item">
              <span class="label">当前用户：</span>
              <el-tag type="info">{{ authStore.userDisplayName }}</el-tag>
            </div>
            <div class="info-item">
              <span class="label">用户角色：</span>
              <el-tag :type="getRoleTagType(authStore.role)">
                {{ getRoleDisplayName(authStore.role) }}
              </el-tag>
            </div>
            <div class="info-item">
              <span class="label">用户权限：</span>
              <div class="permissions-list">
                <el-tag 
                  v-for="permission in authStore.permissions" 
                  :key="permission"
                  size="small"
                  class="permission-tag"
                >
                  {{ getPermissionDisplayName(permission) }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      
      <div class="action-buttons">
        <el-button type="primary" @click="handleRequestPermission" v-if="canRequestPermission">
          <el-icon><Edit /></el-icon>
          申请权限
        </el-button>
        <el-button type="primary" @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回上一页
        </el-button>
        <el-button @click="goToDashboard">
          <el-icon><HomeFilled /></el-icon>
          返回首页
        </el-button>
        <el-button @click="contactAdmin">
          <el-icon><Service /></el-icon>
          联系管理员
        </el-button>
      </div>
      
      <!-- 权限申请历史 -->
      <div v-if="permissionRequests.length > 0" class="permission-requests-history">
        <el-card class="history-card">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>权限申请历史</span>
            </div>
          </template>
          
          <el-timeline>
            <el-timeline-item
              v-for="request in permissionRequests"
              :key="request.id"
              :timestamp="formatDate(request.createdAt)"
              placement="top"
            >
              <el-card>
                <p><strong>申请权限：</strong>{{ getPermissionDisplayName(request.permission) }}</p>
                <p><strong>申请原因：</strong>{{ request.reason }}</p>
                <p>
                  <strong>状态：</strong>
                  <el-tag :type="getStatusType(request.status)">
                    {{ getStatusText(request.status) }}
                  </el-tag>
                </p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </div>
    </div>
    
    <!-- 权限申请表单 -->
    <PermissionRequestForm
      v-model:visible="showRequestForm"
      :target-route="targetRoute"
      :target-title="targetPageTitle"
      :required-permissions="requiredPermissions"
      :required-roles="requiredRoles"
      :error-reason="errorReason"
      @submit="handleRequestSubmitted"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '../store/auth'
import { ElMessage } from 'element-plus'
import PermissionRequestForm from '../components/PermissionRequestForm.vue'
import { 
  Lock, 
  InfoFilled, 
  ArrowLeft, 
  HomeFilled, 
  Service,
  Edit,
  Document
} from '@element-plus/icons-vue'

export default {
  name: 'Forbidden',
  components: {
    PermissionRequestForm,
    Lock,
    InfoFilled,
    ArrowLeft,
    HomeFilled,
    Service,
    Edit,
    Document
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const authStore = useAuthStore()
    
    const showRequestForm = ref(false)
    
    // 从路由query中获取错误详情
    const errorReason = computed(() => route.query.reason || 'PERMISSION_DENIED')
    const requiredPermissionsRaw = computed(() => {
      try {
        return route.query.required ? JSON.parse(route.query.required) : []
      } catch {
        return []
      }
    })
    const requiredRoles = computed(() => {
      if (errorReason.value === 'ROLE_INSUFFICIENT') {
        return requiredPermissionsRaw.value
      }
      return []
    })
    const requiredPermissions = computed(() => {
      if (errorReason.value === 'PERMISSION_DENIED') {
        return requiredPermissionsRaw.value
      }
      return []
    })
    const targetRoute = computed(() => route.query.from || '')
    const targetPageTitle = computed(() => route.query.title || '')
    
    // 错误原因文本
    const errorReasonText = computed(() => {
      if (errorReason.value === 'ROLE_INSUFFICIENT') {
        return '抱歉，您的角色权限不足以访问此页面。'
      } else if (errorReason.value === 'PERMISSION_DENIED') {
        return '抱歉，您缺少访问此页面所需的功能权限。'
      }
      return '抱歉，您没有权限访问此页面。'
    })
    
    // 检查是否可以申请权限
    const canRequestPermission = computed(() => {
      const permission = requiredPermissions.value[0] || requiredRoles.value[0]
      if (!permission) return false
      
      // 检查是否已申请过
      const existingRequest = authStore.hasRequestedPermission(permission)
      return !existingRequest
    })
    
    // 获取权限申请历史
    const permissionRequests = computed(() => {
      return authStore.permissionRequests.filter(r => {
        const permission = requiredPermissions.value[0] || requiredRoles.value[0]
        return r.permission === permission || r.role === permission
      })
    })
    
    onMounted(() => {
      // 加载权限申请记录
      authStore.loadPermissionRequests()
    })
    
    // 返回上一页
    const goBack = () => {
      if (window.history.length > 1) {
        router.go(-1)
      } else {
        router.push('/dashboard')
      }
    }
    
    // 返回首页
    const goToDashboard = () => {
      router.push('/dashboard')
    }
    
    // 联系管理员
    const contactAdmin = () => {
      ElMessage.info('请联系系统管理员获取相应权限')
    }
    
    // 获取角色标签类型
    const getRoleTagType = (role) => {
      const roleTypes = {
        admin: 'danger',
        manager: 'warning',
        agent: 'success',
        customer: 'info'
      }
      return roleTypes[role] || 'info'
    }
    
    // 获取角色显示名称
    const getRoleDisplayName = (role) => {
      const roleNames = {
        admin: '系统管理员',
        manager: '管理员',
        agent: '客服',
        customer: '客户'
      }
      return roleNames[role] || role
    }
    
    // 获取权限显示名称
    const getPermissionDisplayName = (permission) => {
      const permissionNames = {
        'ticket:read': '查看工单',
        'ticket:create': '创建工单',
        'ticket:update': '更新工单',
        'ticket:delete': '删除工单',
        'ticket:assign': '分配工单',
        'user:manage': '用户管理',
        'system:config': '系统配置',
        'report:view': '查看报表',
        'notification:manage': '通知管理',
        'notification:send': '发送通知',
        'file:upload': '上传文件',
        'file:delete': '删除文件',
        'file:manage': '文件管理',
        'admin': '系统管理员',
        'manager': '管理员',
        'agent': '客服'
      }
      return permissionNames[permission] || permission
    }
    
    // 处理权限申请
    const handleRequestPermission = () => {
      showRequestForm.value = true
    }
    
    // 处理申请提交成功
    const handleRequestSubmitted = () => {
      ElMessage.success('权限申请已提交')
      showRequestForm.value = false
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const types = {
        pending: 'warning',
        approved: 'success',
        rejected: 'danger',
        cancelled: 'info'
      }
      return types[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const texts = {
        pending: '待审批',
        approved: '已批准',
        rejected: '已拒绝',
        cancelled: '已取消'
      }
      return texts[status] || status
    }
    
    return {
      authStore,
      showRequestForm,
      errorReason,
      errorReasonText,
      requiredPermissions,
      requiredRoles,
      targetRoute,
      targetPageTitle,
      canRequestPermission,
      permissionRequests,
      goBack,
      goToDashboard,
      contactAdmin,
      getRoleTagType,
      getRoleDisplayName,
      getPermissionDisplayName,
      handleRequestPermission,
      handleRequestSubmitted,
      formatDate,
      getStatusType,
      getStatusText
    }
  }
}
</script>

<style scoped>
.forbidden-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.forbidden-content {
  text-align: center;
  max-width: 600px;
  width: 100%;
}

.error-icon {
  margin-bottom: 30px;
}

.error-title {
  font-size: 48px;
  font-weight: 700;
  color: #f56c6c;
  margin: 0 0 20px 0;
}

.error-description {
  font-size: 18px;
  color: #666;
  margin: 0 0 40px 0;
  line-height: 1.6;
}

.error-details {
  margin-bottom: 40px;
}

.details-card {
  text-align: left;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: var(--text-primary);
}

.permission-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.label {
  font-weight: 500;
  color: var(--text-secondary);
  min-width: 80px;
}

.permissions-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.permission-tag {
  margin: 2px;
}

.action-buttons {
  display: flex;
  gap: 16px;
  justify-content: center;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  min-width: 140px;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.action-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .error-title {
    font-size: 36px;
  }
  
  .error-description {
    font-size: 16px;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: center;
  }
  
  .action-buttons .el-button {
    width: 100%;
    max-width: 300px;
  }
  
  .permission-info {
    gap: 12px;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .label {
    min-width: auto;
  }
}

/* 暗色主题适配 */
.dark .forbidden-container {
  background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
}

.dark .details-card {
  background: rgba(45, 45, 45, 0.95);
  border-color: var(--border-primary);
}

.dark .error-description {
  color: var(--text-secondary);
}
</style>
